/*
 * dac.c
 *
 * Created: 6/18/2013 11:24:53 PM
 *  Author: Tim
 */ 

#include <math.h>
#include "dac.h"
#include "../../board/board.h"
#include "../allocations.h"

void dacSetup()
{
	//Enable use of the DAC via un-Peripheral-"CLOCK"-Blocking it
	prEnable(DAC_PR);
	
	//To get the best ouptut claity possible from the DAC, we need to load the calibration values
	DACB.CH0GAINCAL = ReadCalibrationByte( offsetof(NVM_PROD_SIGNATURES_t, DACB0GAINCAL) );
	DACB.CH0OFFSETCAL = ReadCalibrationByte( offsetof(NVM_PROD_SIGNATURES_t, DACB0OFFCAL) );
	DACB.CH1GAINCAL = ReadCalibrationByte( offsetof(NVM_PROD_SIGNATURES_t, DACB1GAINCAL) );
	DACB.CH1OFFSETCAL = ReadCalibrationByte( offsetof(NVM_PROD_SIGNATURES_t, DACB1OFFCAL) );
	
//	PORTD.DIRSET = 0x0C;
	
	DACB.CTRLB = DAC_CHSEL_DUAL_gc;
	DACB.CTRLC = DAC_REFSEL_AREFB_gc;
	DACB.CTRLA = DAC_CH0EN_bm | DAC_CH1EN_bm;// |DAC_LPMODE_bm;
	//DACB.TIMCTRL = DAC_REfesh;
	DACB.CTRLA |= DAC_ENABLE_bm;
	
	
}



void dacUpdate(uint8_t dacCh, uint16_t data)
{
	if(dacCh & DAC_CH1_bp && daqAlloc.analogAlloc.analogOutCh1Alloc == FEATURE_UTILIZED)	
	{
//		while(!(DACB.STATUS & DAC_CH1DRE_bm));
		DACB.CH1DATA = data;
//		DACB.CTRLB |= DAC_CH1TRIG_bm;
	}
	if(dacCh & DAC_CH0_bp && daqAlloc.analogAlloc.analogOutCh0Alloc == FEATURE_UTILIZED)	
	{
//		while(!(DACB.STATUS & DAC_CH0DRE_bm));
		DACB.CH0DATA = data;
//		DACB.CTRLB |= DAC_CH0TRIG_bm;
	}
	asm("nop");
}
